package ms.maplestory.boot.service;

import ms.maplestory.boot.client.Account;
import ms.maplestory.boot.client.User;
import ms.maplestory.boot.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Service
@RequiredArgsConstructor
public class UserService extends JpaService<User, Integer> {

    private final UserRepository userRepository;

    @Override
    public UserRepository getRepository() {
        return this.userRepository;
    }

    @Transactional
    public User createUser(Account account, int worldId) {
        User user = new User();
        user.setAccount(account);
        user.setWorldId(worldId);
        user.setCharSlotCount(3);
        user.setBuyCharCount(0);
        return save(user);
    }

    public User getAccountByWorldId(Account account, int worldId) {
        User user = null;
        if (!CollectionUtils.isEmpty(account.getUsers())) {
            user = account.getUserByWorldId(worldId);
        }
        if (user == null) {
            user = getRepository().findByAccountIdAndWorldId(account.getId(), worldId);
            if (user != null) account.addUser(user);
        }
        return user;
    }
}
